"""
User Service for TaskMaster v1
AceFlow v3.0 - Implementation Phase

Handles user authentication and management
"""

from typing import Optional
from ..models.database import User, get_db_manager
from ..utils.auth_utils import get_password_hash, verify_password, create_access_token


class UserService:
    """User service for authentication and user management"""

    def __init__(self):
        self.db_manager = get_db_manager()

    def register_user(self, username: str, password: str, email: Optional[str] = None) -> dict:
        """
        Register a new user

        Args:
            username: Unique username
            password: Plain text password
            email: Optional email address

        Returns:
            dict: Registration result with success status and user info
        """
        try:
            # Validate input
            if not username or not username.strip():
                return {
                    "success": False,
                    "message": "用户名不能为空",
                    "user_id": None
                }

            if not password or not password.strip():
                return {
                    "success": False,
                    "message": "密码不能为空",
                    "user_id": None
                }

            # Check if username already exists
            if self._username_exists(username):
                return {
                    "success": False,
                    "message": "用户名已存在",
                    "user_id": None
                }

            # Hash password
            password_hash = get_password_hash(password)

            # Create user
            with self.db_manager.get_connection() as conn:
                # Insert user with explicit id
                # Find the next available id
                result = conn.execute("SELECT COALESCE(MAX(id), 0) + 1 FROM users")
                next_id = result.fetchone()[0]

                conn.execute("""
                    INSERT INTO users (id, username, password_hash, email)
                    VALUES (?, ?, ?, ?)
                """, [next_id, username, password_hash, email])

                user_id = next_id

                return {
                    "success": True,
                    "message": "用户注册成功",
                    "user_id": user_id
                }

        except Exception as e:
            print(f"Registration error: {str(e)}")  # Debug logging
            return {
                "success": False,
                "message": f"注册失败: {str(e)}",
                "user_id": None
            }

    def authenticate_user(self, username: str, password: str) -> dict:
        """
        Authenticate user login

        Args:
            username: Username
            password: Plain text password

        Returns:
            dict: Authentication result with token if successful
        """
        try:
            # Get user from database
            user_data = self._get_user_by_username(username)
            if not user_data:
                return {
                    "success": False,
                    "message": "用户名或密码错误",
                    "token": None,
                    "user_id": None
                }

            # Verify password
            if not verify_password(password, user_data["password_hash"]):
                return {
                    "success": False,
                    "message": "用户名或密码错误",
                    "token": None,
                    "user_id": None
                }

            # Create access token
            token_data = {"sub": str(user_data["id"])}
            access_token = create_access_token(token_data)

            return {
                "success": True,
                "message": "登录成功",
                "token": access_token,
                "user_id": user_data["id"]
            }

        except Exception as e:
            return {
                "success": False,
                "message": f"登录失败: {str(e)}",
                "token": None,
                "user_id": None
            }

    def get_user_by_id(self, user_id: int) -> Optional[dict]:
        """
        Get user information by ID (without password hash)

        Args:
            user_id: User ID

        Returns:
            dict: User information or None if not found
        """
        try:
            with self.db_manager.get_connection() as conn:
                result = conn.execute("""
                    SELECT id, username, email, avatar, created_at
                    FROM users
                    WHERE id = ?
                """, [user_id])

                row = result.fetchone()
                if row:
                    return {
                        "id": row[0],
                        "username": row[1],
                        "email": row[2],
                        "avatar": row[3],
                        "created_at": str(row[4]) if row[4] else None
                    }
                return None

        except Exception:
            return None

    def _username_exists(self, username: str) -> bool:
        """Check if username already exists"""
        try:
            with self.db_manager.get_connection() as conn:
                result = conn.execute(
                    "SELECT COUNT(*) FROM users WHERE username = ?",
                    [username]
                )
                count = result.fetchone()[0]
                return count > 0
        except Exception:
            return False

    def _get_user_by_username(self, username: str) -> Optional[dict]:
        """Get user data by username"""
        try:
            with self.db_manager.get_connection() as conn:
                result = conn.execute("""
                    SELECT id, username, password_hash, email, avatar, created_at
                    FROM users
                    WHERE username = ?
                """, [username])

                row = result.fetchone()
                if row:
                    return {
                        "id": row[0],
                        "username": row[1],
                        "password_hash": row[2],
                        "email": row[3],
                        "avatar": row[4],
                        "created_at": row[5]
                    }
                return None

        except Exception:
            return None


# Global user service instance
user_service = UserService()


def get_user_service() -> UserService:
    """Get user service instance"""
    return user_service
